package com.mapler.utility;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import org.apache.log4j.Logger;
//import org.apache.commons.codec.binary.Base64;

/**
 * @author jar
 */
public class HttpHelper {

    private static Logger log = Logger.getLogger(HttpHelper.class);

    public static String post(URL url, String content) throws Exception {
        return sendReq(url, content, "POST");
    }

    public static String get(URL url) throws Exception {
        return sendReq(url, "", "GET");
    }

    public static String sendReq(URL url, String content, String reqType) throws Exception {
        HttpURLConnection conn = null;
        String result = "";
        try {
            conn = (HttpURLConnection) url.openConnection();
            if (reqType.equalsIgnoreCase("POST")) {
                writeData(content, "text/xml", conn, reqType);
            }
            result = read(conn);
        } catch (Exception e) {
            throw e;
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
        return result;
    }

    private static void XwriteData(String content, String contentType, HttpURLConnection conn, String reqType) throws Exception {

        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod(reqType);
        conn.setRequestProperty("Content-Type", contentType);
        conn.setRequestProperty("Accept-Charset", "UTF-8");
        conn.setRequestProperty("Content-Length", "50007");

        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
        try {
            writer.write(content);
        } catch (Exception ec) {
            ec.printStackTrace();
        } finally {
            writer.close();
        }
    }

    private static void writeData(String content, String contentType, HttpURLConnection conn, String reqType) throws Exception {
        DataOutputStream wr = null;
        try {
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod(reqType);
            conn.setRequestProperty("Content-Type", contentType);
            conn.setRequestProperty("Accept-Charset", "UTF-8");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Content-Length", ""
                    + Integer.toString(content.getBytes().length + 7));
            conn.setRequestProperty("Content-Language", "en-US");
            conn.setUseCaches(false);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            wr = new DataOutputStream(conn.getOutputStream());

            wr.writeBytes(content);
            wr.flush();
            wr.close();
            OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

            writer.write(content);
        } catch (Exception ec) {
            ec.printStackTrace();
        } finally {
            if (wr != null) {
                wr.close();
            }
        }
    }

    public static String Xread(HttpURLConnection conn) throws IOException {
        InputStream is = conn.getInputStream();
        Charset charset = Charset.forName("UTF8");
        InputStreamReader isr = new InputStreamReader(is, charset);

        int numCharsRead;
        char[] charArray = new char[1024];
        StringBuffer sb = new StringBuffer();
        while ((numCharsRead = isr.read(charArray)) > 0) {
            sb.append(charArray, 0, numCharsRead);
        }
        String result = sb.toString();
        return result;
    }

    public static String read(HttpURLConnection conn) throws IOException {
        try {
            InputStream is = conn.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = rd.readLine()) != null) {
                response.append(line);
                response.append('\r');
            }
            rd.close();
            return response.toString();
        } catch (Throwable ex) {
            log.error("Error "+ex);
            ex.printStackTrace();
        }
        return "<Response><errorcode>000</errorcode><message>Request failed.</message></Response>";
    }
}
